/**
 * FileDownLoader.java
 * Retrieves the specified file from the blobstore for user download. 
 */
package com.example.myproject;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.files.AppEngineFile;
import com.google.appengine.api.files.FileReadChannel;
import com.google.appengine.api.files.FileService;
import com.google.appengine.api.files.FileServiceFactory;
import com.google.appengine.api.files.LockException;
   
public class FileDownLoader extends HttpServlet {  
   
private static final long serialVersionUID = -1292621693229536247L;  

	final private int MAXSIZE = 50 * 1024;

	protected void doPost( HttpServletRequest req, HttpServletResponse resp)	
			throws IOException{
		
		final String FILESYSTEM = "/blobstore/";
		
		Long id = Long.parseLong(req.getParameter("id"));
		Long parentid = Long.parseLong(req.getParameter("parentid"));
		
		UploadDAO dao = new UploadDAO();
		UploadDTO dto = null;
		
		// Find the file in the blobstore.
		if(parentid != 0)
		{
			dto =  dao.findById(parentid);
		}
		else
		{
			dto =  dao.findById(id);
		}
		AppEngineFile AFE = new AppEngineFile(FILESYSTEM + dto.getPath());
		BlobKey bk = FileServiceFactory.getFileService().getBlobKey(AFE);
		
		if ("audio/mpeg".equals(dto.getContentType())){				//mp3
			resp.setContentType("audio/mpeg");
		} else if("text/plain".equals(dto.getContentType())){		//text
			resp.setContentType("text/plain");
		} else if("image/jpeg".equals(dto.getContentType())){		// jpeg
			resp.setContentType("image/jpeg");
		} else if("image/pjpeg".equals(dto.getContentType())){		// pjpeg
			resp.setContentType("image/pjpeg");
		} else if("image/gif".equals(dto.getContentType())){		// gif
			resp.setContentType("image/gif");
		} else if("application/pdf".equals(dto.getContentType())){	// pdf
			resp.setContentType("application/pdf");
		} else if("application/ogg".equals(dto.getContentType())){	// ogg
			resp.setContentType("application/ogg");
		} else if("image/bmp".equals(dto.getContentType())){		// bmp
			resp.setContentType("image/bmp");
		} else if("video/x-msvideo".equals(dto.getContentType())){	// avi
			resp.setContentType("video/x-msvideo");
		}
		
		resp.setHeader("Content-Disposition", "attachment; filename=\"" + dto.getTitle() + "\"");
		
	    FileService fileService = FileServiceFactory.getFileService();
	    AppEngineFile file = null;
	    
	    try {
	    	file = fileService.getBlobFile(bk);
	    } catch (FileNotFoundException e) {
	    	e.printStackTrace();
	    }
	    
	    FileReadChannel ch = null;
	    
		try {
			ch = fileService.openReadChannel(file, false);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (LockException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		byte[] barray = new byte[MAXSIZE];

	    ByteArrayOutputStream baos = new ByteArrayOutputStream();

	    try {
	    	ByteBuffer bb = ByteBuffer.wrap(barray);
	    	int nRead;
	    	while ((nRead=ch.read(bb)) > 0 ) {
	    		for (int i=0; i < nRead; i++) {
	    			try {
	    				baos.write(barray[i]);
	    			} catch (Exception e) {
	    				e.printStackTrace();
	    			}
	    		}
	    		bb.clear();
	    	}
    	} catch (IOException e) {
    		e.printStackTrace();
	    }
	    
	    try{

	    	resp.getOutputStream().write(baos.toByteArray());
	    	
	    }catch (IllegalStateException e){
	    	System.out.println("Error: IllegalStateException");
	    	e.printStackTrace();
	    }
	    	
	    baos.flush();
	    baos.close();
	    
	}
	
}